<?php

class Nonce{
	protected $default_salt = '';
	protected $name         = '';  
	protected $mid = 0;
	/* each from should give its own name
	 * name can be the URL / section name ???
	 */
	function __construct($name, $mid=0){    
    global $site_global_config;
    $this->mid  = $mid;
    $this->name = $name;
    $this->default_salt  = get_hash_param($site_global_config, 'DEFAULT_SALT', 'iosu129d0asd2dfn');
	}
	
	

  # based on user's account
  #    secret salt and possibly timestamp
  # for preventing XSRF
	/**
	 * Creates a random, one time use token.
	 *
	 * @since 2.0.3
	 *
	 * @param string|int $action Scalar value to add context to the nonce.
	 * @return string The one use form token
	 */
	function create() {
		$name = $this->name;
	  $mid  = $this->mid;
	  $tick = $this->tick(); #  time related factor
	  
	  return substr($this->hash($tick . $name . $mid, 'nonce'), -12, 10);
	}
	
	# original function name: nonce_tick
	function tick() {
    $nonce_life = 86400;
    return ceil(time() / ( $nonce_life / 2 ));
  }
	  
	/**
	 * Verify that correct nonce was used with time limit.
	 *
	 * The user is given an amount of time to use the token, so therefore, since the
	 * UID and $action remain the same, the independent variable is the time.
	 *
	 * @since 2.0.3
	 *
	 * @param string $nonce Nonce that was used in the form to verify
	 * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
	 * @return bool Whether the nonce check passed or failed.
	 */
	function verify($nonce) {
		$name = $this->name;
	  $mid = $this->mid;
	
	  $tick = $this->tick();
	
	  // Nonce generated 0-12 hours ago
	  if ( substr($this->hash($tick . $name . $mid, 'nonce'), -12, 10) == $nonce )
	    return 1;
	  // Nonce generated 12-24 hours ago
	  if ( substr($this->hash(($tick - 1) . $name . $mid, 'nonce'), -12, 10) == $nonce )
	    return 2;
	  // Invalid nonce
	  return false;
	}


  /* current salt didn't depends on scheme.... 
   * add more random factor later 
   */
	function salt(){
		return $this->default_salt;
	}


	/**
	 * Get hash of given string.
	 *
	 * @since 2.0.3
	 * @uses wp_salt() Get WordPress salt
	 *
	 * @param string $data Plain text to hash
	 * @return string Hash of $data
	 */
	function hash($data) {
	  $salt = $this->salt();
	  return hash_hmac('md5', $data, $salt);
	}	
 
} # end Class Nonce
?>